package com.zhongshengnetwork.rightbe.https;

import android.net.Uri;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by GordonLjx on 2016/9/18.
 */
public class MyJsonObjectRequest extends JsonRequest<JSONObject> {//
    String stringRequest;

    /**
     * 这里的method必须是Method.POST，也就是必须带参数。
     * 如果不想带参数，可以用JsonObjectRequest，给它构造参数传null。GET方式请求。
     * @param stringRequest 格式应该是 "key1=value1&key2=value2"
     */

    public MyJsonObjectRequest(String url, String stringRequest,
                               Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url,stringRequest , listener, errorListener);
        this.stringRequest = stringRequest;
    }

    @Override
    public String getBodyContentType() {
        return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
    }


    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    public static String appendParameter(String url,Map<String,String> params){
        Uri uri = Uri.parse(url);
        Uri.Builder builder = uri.buildUpon();
        for(Map.Entry<String,String> entry:params.entrySet()){
            //builder.appendQueryParameter(entry.getKey(),entry.getValue());
            if (entry.getValue() instanceof String){
                try {
                    //2021-03-27日解决在使用url的queryString传递参数时，包含特殊字符：&、+、/、=等等，会出现内容丢失问题，故而需要读参数使用URLEncoder.encode操作，tomcat会自动decode
                    builder.appendQueryParameter(entry.getKey(), URLEncoder.encode((String) entry.getValue(),"UTF-8"));
                }catch (Exception e){
                    builder.appendQueryParameter(entry.getKey(),entry.getValue());
                }
            }else {
                builder.appendQueryParameter(entry.getKey(),entry.getValue());
            }
        }
        return builder.build().getQuery();
    }



}
